<template>
  <div class="publisher-audit">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-radio-group v-model="currentStatus" @change="handleStatusChange">
        <el-radio-button :value="'all'">全部</el-radio-button>
        <el-radio-button :value="0">待审核</el-radio-button>
        <el-radio-button :value="1">已审核</el-radio-button>
        <el-radio-button :value="2">已拒绝</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="filteredPublisherList"
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无数据"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="发行商名称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="150" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="createdTime" label="申请时间" width="160" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success" size="small">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 0" type="warning" size="small">待审核</el-tag>
            <el-tag v-else type="danger" size="small">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="primary"
              size="small"
              plain
              @click="handleAudit(scope.row)"
            >
              审核
            </el-button>
            <el-button
              v-else
              type="info"
              size="small"
              plain
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="发行商资质审核"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="audit-content">
        <div class="info-item">
          <span class="label">发行商许可证：</span>
          <el-image
            :src="getImageUrl(currentPublisher.licenseFile)"
            style="width: 120px; height: 120px; border-radius: 4px; border: 1px solid #dcdfe6;"
            fit="cover"
            :preview-src-list="[getImageUrl(currentPublisher.licenseFile)]"
            preview-teleported
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>
        </div>
        <div class="info-item">
          <span class="label">发行商名称：</span>
          <span>{{ currentPublisher.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">邮箱：</span>
          <span>{{ currentPublisher.email }}</span>
        </div>
        <div class="info-item">
          <span class="label">手机号：</span>
          <span>{{ currentPublisher.phone }}</span>
        </div>
        <div class="info-item">
          <span class="label">申请时间：</span>
          <span>{{ currentPublisher.createdTime }}</span>
        </div>

        <div class="audit-action">
          <span class="label">审核结果：</span>
          <el-radio-group v-model="auditResult">
            <el-radio :value="1">通过</el-radio>
            <el-radio :value="2">拒绝</el-radio>
          </el-radio-group>
        </div>

        <div class="audit-remark">
          <span class="label">审核备注：</span>
          <el-input
            v-model="auditRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注（选填）"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmAudit"
          :loading="auditLoading"
        >
          确认审核
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getPublisherListAPI } from '@/api/publisher'
import { updatePublisherStatusAPI } from '@/api/publisher'
import { onMounted, ref, computed } from 'vue'
import { Picture } from '@element-plus/icons-vue'

// 图片基础URL - 根据你的后端配置调整
const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL

// 响应式数据
const publisherList = ref([])
const currentStatus = ref('all') // 当前筛选状态：all, 0, 1
const loading = ref(false)

// 审核对话框相关
const auditDialogVisible = ref(false)
const currentPublisher = ref({})
const auditResult = ref(1) // 1: 通过, 2: 拒绝
const auditRemark = ref('')
const auditLoading = ref(false)

// 计算属性：根据状态筛选数据
const filteredPublisherList = computed(() => {
  if (currentStatus.value === 'all') {
    return publisherList.value
  }
  return publisherList.value.filter(item => item.status === currentStatus.value)
})

// 页面加载时获取数据
onMounted(() => {
  getPublisherList()
})

// 获取完整的图片URL
const getImageUrl = (relativePath: string) => {
  if (!relativePath) return ''
  // 如果已经是完整URL，直接返回
  if (relativePath.startsWith('http')) {
    return relativePath
  }
  // 拼接完整URL
  console.log('BASE_IMAGE_URL', BASE_IMAGE_URL)
  return `${BASE_IMAGE_URL}/${relativePath}`
}

// 获取发行商列表
const getPublisherList = async () => {
  loading.value = true
  try {
    const { data: res } = await getPublisherListAPI()
    if (res.code !== 1) {
      ElMessage.error(res.msg || '获取发行商信息失败')
      return
    }
    publisherList.value = res.data || []
  } catch {
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 状态筛选变化处理
const handleStatusChange = () => {
  // 可以在这里添加额外的逻辑，比如统计等
}

// 处理审核操作
const handleAudit = (row) => {
  console.log('handleAudit', row)
  currentPublisher.value = { ...row }
  auditResult.value = 1
  auditRemark.value = ''
  auditDialogVisible.value = true
}

// 处理查看操作
const handleView = (row) => {
  ElMessageBox.alert(
    `
    <div style="text-align: left;">
      <p><strong>发行商名称：</strong>${row.name}</p>
      <p><strong>邮箱：</strong>${row.email}</p>
      <p><strong>手机号：</strong>${row.phone}</p>
      <p><strong>申请时间：</strong>${row.createdTime}</p>
      <p><strong>审核状态：</strong>${row.status === 1 ? '已通过' : row.status === 2 ? '已拒绝' : '待审核'}</p>
      ${row.auditTime ? `<p><strong>审核时间：</strong>${row.auditTime}</p>` : ''}
      ${row.auditRemark ? `<p><strong>审核备注：</strong>${row.auditRemark}</p>` : ''}
    </div>
    `,
    '发行商详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 确认审核
const confirmAudit = async () => {
  if (!auditResult.value) {
    ElMessage.warning('请选择审核结果')
    return
  }

  auditLoading.value = true
  try {
    const { data: res } = await updatePublisherStatusAPI({
      id: currentPublisher.value.id,
      status: auditResult.value,
      remark: auditRemark.value
    })
    console.log('res', res)

    if (res.code !== 1) {
      ElMessage.error(res.msg || '审核失败')
      return
    }

    // 更新本地数据
    const index = publisherList.value.findIndex(item => item.id === currentPublisher.value.id)
    if (index !== -1) {
      publisherList.value[index].status = auditResult.value
      publisherList.value[index].auditTime = new Date().toLocaleString()
      publisherList.value[index].auditRemark = auditRemark.value
    }

    ElMessage.success('审核完成')
    auditDialogVisible.value = false

  } catch {
    ElMessage.error('审核失败，请重试')
  } finally {
    auditLoading.value = false
  }
}

</script>

<style scoped>
.publisher-audit {
  padding: 20px;
  background-color: #fff;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

/* 审核对话框样式 */
.audit-content {
  padding: 10px 0;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.5;
}

.info-item .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
  flex-shrink: 0;
}

.audit-action {
  display: flex;
  align-items: center;
  margin: 20px 0 16px 0;
}

.audit-action .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
  flex-shrink: 0;
}

.audit-remark {
  margin-top: 16px;
}

.audit-remark .label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-weight: 500;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: 1px solid #ebeef5;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

/* 按钮组样式 */
:deep(.el-radio-group .el-radio-button__inner) {
  border-color: #dcdfe6;
  color: #606266;
}

:deep(.el-radio-group .el-radio-button__original:checked + .el-radio-button__inner) {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

/* 图片加载失败样式 */
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
}

.image-slot .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}
</style>
